package com.fzrskj.cloud.free.sys.utils;

import com.fzrskj.cloud.free.core.enums.DicParamEnum;
import com.fzrskj.cloud.free.core.utils.CloudContextUtils;
import com.fzrskj.cloud.free.dic.bean.DicParam;
import com.fzrskj.cloud.free.dic.utils.DicParamUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.http.HttpStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * AgentRequestUtils.
 *
 * @author zj.
 *         Created on 2019/5/10 0010.
 */
public class HtmlTplUtils {
    public static Map<String, String> map = new HashedMap();
    static {
        map.put("index.html", "tpl.index.html");
        map.put("domain-domain.html", "tpl.domain-domain.html");
        map.put("domain-register.html", "tpl.domain-register.html");
        map.put("cloud-index.html", "tpl.cloud-index.html");
        map.put("cloud-register.html", "tpl.cloud-register.html");
        map.put("cloud-aliyun-ecs.html", "tpl.cloud-aliyun-ecs.html");
        map.put("cloud-huawei-ecs.html", "tpl.cloud-huawei-ecs.html");
        map.put("cloud-baidu-bcc.html", "tpl.cloud-baidu-bcc.html");
        map.put("vhost-index.html", "tpl.vhost-index.html");
        map.put("vhost-register.html", "tpl.vhost-register.html");
        map.put("vhost-baidu-register.html", "tpl.vhost-baidu-register.html");
        map.put("diy-index.html", "tpl.diy-index.html");
        map.put("diy-buy.html", "tpl.diy-buy.html");
        map.put("user-find-pass.html", "tpl.user-find-pass.html");
        map.put("user-find-pass-complete.html", "tpl.user-find-pass-complete.html");
        map.put("user-find-pass-confirm.html", "tpl.user-find-pass-confirm.html");
        map.put("user-find-pass-reset.html", "tpl.user-find-pass-reset.html");
        map.put("user-login.html", "tpl.user-login.html");
        map.put("user-reg-activity.html", "tpl.user-reg-activity.html");
        map.put("user-register.html", "tpl.user-register.html");
        map.put("about/about.html", "about/tpl.about.html");
        map.put("news/news.html", "news/tpl.news.html");
        map.put("news/newsinfo.html", "news/tpl.newsinfo.html");
        map.put("notice/notice.html", "notice/tpl.notice.html");
        map.put("notice/noticeinfo.html", "notice/tpl.noticeinfo.html");
        map.put("notice/serviceagree.html", "notice/tpl.serviceagree.html");
        map.put("register/regsucess.html", "register/tpl.regsucess.html");
        map.put("support/about.html", "support/tpl.about.html");
        map.put("support/support.html", "support/tpl.support.html");
        map.put("support/detail.html", "support/tpl.detail.html");
        map.put("usercenter/shopping/domainmaterial.html", "usercenter/shopping/tpl.domainmaterial.html");
        map.put("usercenter/shopping/payment.html", "usercenter/shopping/tpl.payment.html");
        map.put("usercenter/shopping/settlement.html", "usercenter/shopping/tpl.settlement.html");
        map.put("usercenter/shopping/shoppinglist.html", "usercenter/shopping/tpl.shoppinglist.html");
        map.put("control-login.html", "tpl.control-login.html");
        map.put("controlPanel.html", "tpl.control-login.html");
    }

    /**
     * make cache html.
     * @param request HttpServletRequest
     * @param uri uri
     */

    public static boolean doCache(HttpServletRequest request, HttpServletResponse response, String uri) {
        if (CloudContextUtils.getAgentId() > 0) {
            return false;
        }
        String tmpDir = DicParamUtils.getParamValue(DicParamEnum.TEMPLATE_KEY.getVal());
        uri = uri.replaceAll(tmpDir, "").replaceAll(tmpDir.substring(0, tmpDir.length()-1) + "-", "");
        final String executeUri = uri;
        if (map.containsKey(uri)) {
            return reallyDo(request, response, executeUri, tmpDir);
        }
        return false;
    }

    /**
     * 获取并保存.
     * @param request
     * @param uri
     * @param tmpDir
     */
    static boolean reallyDo(HttpServletRequest request, HttpServletResponse response, String uri, String tmpDir) {
        //如果存在，异步更新，不存在，时实更新
        String rootDir = request.getSession().getServletContext().getRealPath("/");
        String savePath = rootDir + tmpDir.substring(1) + uri;
        File file = new File(savePath);
        /*if (file.exists()) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    makeHtml(savePath, rootDir, tmpDir, uri);
                }
            }).start();
            return false;
        } else {*/
            String html = makeHtml(savePath, rootDir, tmpDir, uri);
            response.setHeader("Content-Type", "text/html");
            response.setStatus(HttpStatus.SC_OK);
            try {
                response.getOutputStream().write(html.getBytes("UTF-8"));
            } catch (IOException e) {
                e.printStackTrace();
            }
            return true;
        //}
    }

    static String makeHtml(String savePath, String rootDir, String tmpDir, String uri) {
        //获取模板
        String html = getTplContent(rootDir, tmpDir, map.get(uri));
        String keywords = DicParamUtils.getParamValue("keywords");
        String description = DicParamUtils.getParamValue("description");
        String webtitle = DicParamUtils.getParamValue("webtitle");
        html = html.replaceAll("\\[标题]",webtitle);
        html = html.replaceAll("\\[关键字]",keywords);
        html = html.replaceAll("\\[描述]",description);

        DicParamUtils paramUtils = new DicParamUtils();
        List<DicParam> paramList = paramUtils.getListDicParam(1);
        for (DicParam param : paramList) {
            html = html.replaceAll("\\[" + param.getParamName() + "]", param.getParamValue());
        }

        //保存
        save(html, savePath);
        return html;
    }

    /**
     * 是否可以缓存
     * @param uri
     * @return
     */
    synchronized static Boolean canCache(String uri) {
        return true;
    }

    final static String regex = "<hl-tpl hl-include=\"([0-9a-zA-Z._]+)\" />";
    static Pattern pattern = Pattern.compile(regex);

    static String getTplContent(String rootDir, String tmpDir, String uri) {
        String tplPath = rootDir + tmpDir.substring(1) + uri;
        String html = getFileContent(tplPath);
        Matcher matcher = pattern.matcher(html);
        while (matcher.find()) {
            String include = matcher.group();
            String includeUri = include.substring(include.indexOf("\"") + 1);
            includeUri = includeUri.substring(0, includeUri.indexOf("\""));
            html = html.replace(include, getTplContent(rootDir, tmpDir, includeUri));
        }
        return html;
    }

    static String getFileContent(String filePath) {
        File file = new File(filePath);
        String content = "";
        if(!file.exists()){
            throw new RuntimeException("template not found: "  + filePath);
        }
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
            String line = null;
            while ((line = reader.readLine()) != null) {
                content += line;
            }
        } catch (Exception e) {

        } finally {
            if (null != reader) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return content;
    }


    /**
     * 写入文件内容.
     * @param html html content.
     * @param savePath path.
     */
    static void save(String html, String savePath) {
        BufferedWriter writer = null;
        try {
            //目标文件组成
            //检查是否存在，不存在创建.
            File file = new File(savePath);
            if(!file.exists()){
                file.createNewFile();
            }
            //写内容
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
            writer.write(html);
            writer.flush();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != writer) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 公共错误路径替换.
     * @param html html.
     * @return html.
     */
    private static String publicReplace(String html, String uri) {
        /*html = html.replaceAll("public/js/extend/layer.ext.js", "public/layer/extend/layer.ext.js");
        html = html.replaceAll("public/js/need/laydate.css", "public/laydate/need/laydate.css");
        html = html.replaceAll("public/js/skins/default/laydate.css", "public/laydate/skins/default/laydate.css");
        html = html.replaceAll("public/js/skin/layer.css", "public/layer/skin/layer.css");
        html = html.replaceAll("public/js/skin/layer.ext.css", "public/layer/skin/layer.ext.css");*/
        return html;
    }
}
